package m.jclecai.com.fragment;


import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.AccountInfoActivity;
import m.jclecai.com.activity.AlterNicknameActivity;
import m.jclecai.com.activity.BalanceActivity;
import m.jclecai.com.activity.BindIDCardActivity;
import m.jclecai.com.activity.BindbankCardActivity;
import m.jclecai.com.activity.LoginActivity;
import m.jclecai.com.activity.MainActivity;
import m.jclecai.com.activity.RechargeActivity;
import m.jclecai.com.activity.RechargePayActivity;
import m.jclecai.com.activity.RedPkgActivity;
import m.jclecai.com.activity.RedPkgManagerActivity;
import m.jclecai.com.activity.SettingActivity;
import m.jclecai.com.activity.ShowInvitedFriendActivity;
import m.jclecai.com.activity.UserInfoActivity;
import m.jclecai.com.activity.VoteRecordActivity;
import m.jclecai.com.activity.WithdrawActivity;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.BankBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.AutoSwipeRefreshLayout;
import m.jclecai.com.view.rounded.RoundedImageView;


/**
 * 我的彩票
 */
public class UserFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.iv_icon)
    RoundedImageView ivIcon;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_onclick_login)
    TextView tvOnclickLogin;
    @BindView(R.id.tv_user_money)
    TextView tvUserMoney;
    @BindView(R.id.tv_redpkg)
    TextView tv_redpkg;
    @BindView(R.id.srl)
    AutoSwipeRefreshLayout srl;
    @BindView(R.id.tv_name)
    TextView tvName;

    UserBean userBean;
    BankBean bankBean;


    @BindView(R.id.tv_nickname)
    TextView mTvNickname;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_user;
    }

    @Override
    public void initData() {
        userBean = PreferenceUtil.readUser(getActivity());
        bankBean = PreferenceUtil.getDefaultWithDrawBank(getActivity());

        if (bankBean == null && userBean != null) {
            //这里表示如果本地没有默认的银行卡的话，使用UserBean中的
            bankBean=userBean.createBankBean();
        }

        srl.setOnRefreshListener(this);
        srl.setRefreshing(true);
        updateText();
        getUserInfo();

    }




    void getUserInfo() {
//        showDialog();
        String userName = PreferenceUtil.getUserName(getActivity());
        String password = PreferenceUtil.getPassword(getActivity());
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                if (srl != null)
                    srl.setRefreshing(false);
            }

            @Override
            public void onResponse(String response) {
                if (srl != null)
                    srl.setRefreshing(false);
                dissDialog();
                UserBean usb = FastOk.get(response, UserBean.class);
                if (usb == null) {
                    DisPlay(setString(R.string.error_network));
                    return;
                }
                userBean = usb;
                if ("1011".equals(usb.getStatus())) {//未登录返回首页 ios 逻辑
                    userBean = null;
                }
                if (getActivity() == null) {
                    return;
                }
                PreferenceUtil.writeUser(getActivity(), userBean);
                updateText();
            }
        }, pair);
    }

    @Override
    public void onResume() {
        super.onResume();
        userBean = PreferenceUtil.readUser(getActivity());
        bankBean = PreferenceUtil.getDefaultWithDrawBank(getActivity());
        if (bankBean == null && userBean != null) {
            //如果银行为空，设置一个默认的；
            bankBean=userBean.createBankBean();
            PreferenceUtil.setDefaultWithDrawBank(getActivity(),bankBean);
        }
        getUserInfo();
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果未登录则显示首页
        if (Constant_Result.SHOWUSERFRAGMENT == requestCode && resultCode != FragmentActivity.RESULT_OK) {
            ((MainActivity) getActivity()).selectHomeTab();
        } else if (Constant_Result.CLEARALLUSERDATA == requestCode && resultCode == FragmentActivity.RESULT_OK) {
            //如果清除登录信息则调用登录
            startActivityForResult(new Intent(getActivity(), LoginActivity.class), Constant_Result.SHOWUSERFRAGMENT);
        } else if (Constant_Result.BINDBANK == requestCode && resultCode == FragmentActivity.RESULT_OK) {
            //点击提现
            startActivity(new Intent(getActivity(), WithdrawActivity.class));
        } else if (Constant_Result.BINDCARD == requestCode && resultCode == FragmentActivity.RESULT_OK) {
            //如果没有绑定银行卡 先去绑定银行卡
            if (bankBean == null) {
                startActivityForResult(new Intent(getActivity(), BindbankCardActivity.class),
                        Constant_Result.BINDBANK);
                return;
            } else {
                //点击提现
                startActivity(new Intent(getActivity(), WithdrawActivity.class));
            }
        }
    }

    @OnClick({R.id.rl_user, R.id.tv_name, R.id.iv_icon, R.id.rl_pinformation, R.id.rl_hongbao,
            R.id.rl_hongbao_manager, R.id.rl_chongzhi, R.id.rl_tixian, R.id.rl_touzhu,
            R.id.rl_zhuihao, R.id.rl_shezhi, R.id.rl_hemai,R.id.rl_user_nickname,R.id.ll_tui_guang})
    public void onClick(View view) {
        srl.setRefreshing(false);
        if (!isLogin() || userBean == null) {
            startActivityForResult(new Intent(getActivity(), LoginActivity.class),
                    Constant_Result.SHOWUSERFRAGMENT);
            return;
        }
        switch (view.getId()) {
            case R.id.iv_icon:
            case R.id.tv_name:
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
                break;
            case R.id.rl_user:
                startActivityForResult(new Intent(getActivity(), AccountInfoActivity.class),
                        Constant_Result.CLEARALLUSERDATA);
                break;
            case R.id.rl_pinformation:
                //点击账户余额
                //判断是否登录
                BaseUtils.startAcy(getActivity(), BalanceActivity.class);
                break;
            case R.id.rl_hongbao:
                //点击红包,先判断是否登录
                BaseUtils.startAcy(getActivity(), RedPkgActivity.class);
                break;
            case R.id.rl_hongbao_manager:
                //点击红包,先判断是否登录
                BaseUtils.startAcy(getActivity(), RedPkgManagerActivity.class);
                break;
            case R.id.rl_chongzhi:
                //点击充值
                BaseUtils.startAcy(getActivity(), RechargeActivity.class);
//                BaseUtils.startAcy(getActivity(), RechargePayActivity.class);
                break;
            case R.id.rl_tixian:
                //如果没有绑定身份证，先去绑定身份证
                if (TextUtils.isEmpty(userBean.getIdcard())) {
                    startActivityForResult(new Intent(getActivity(), BindIDCardActivity.class),
                            Constant_Result.BINDCARD);
                    return;
                }
                //如果没有绑定银行卡 先去绑定银行卡
               /* if (bankBean == null) {
                    startActivityForResult(new Intent(getActivity(), BindbankCardActivity.class),
                            Constant_Result.BINDBANK);
                    return;
                }*/
                //点击提现
                startActivity(new Intent(getActivity(), WithdrawActivity.class));
                break;
            case R.id.rl_touzhu:
                //点击投注
                startActivity(new Intent(getActivity(), VoteRecordActivity.class)
                        .putExtra("index", 0)
                        .putExtra("title", "购买记录"));
                break;
            case R.id.rl_zhuihao:
                //点击追号
                startActivity(new Intent(getActivity(), VoteRecordActivity.class)
                        .putExtra("index", 1)
                        .putExtra("title", "追号记录"));
                break;
            case R.id.rl_shezhi:
                //点击设置
                startActivityForResult(new Intent(getActivity(), SettingActivity.class),
                        Constant_Result.CLEARALLUSERDATA);
                break;
            case R.id.rl_hemai:
                //点击合买
                startActivity(new Intent(getActivity(), VoteRecordActivity.class)
                        .putExtra("index", 2)
                        .putExtra("title", "合买记录"));
                break;
            case R.id.rl_user_nickname:
                startActivity(new Intent(getActivity(),AlterNicknameActivity.class));
                break;
            case R.id.ll_tui_guang:
                startActivity(new Intent(getActivity(), ShowInvitedFriendActivity.class));
                break;
        }
    }

    void updateText() {
        //safe 2 - 中
        tvOnclickLogin.setText("");
        tvLogin.setText("未登录");
        tvUserMoney.setText(("0.00元"));
        tv_redpkg.setText(("0.00元"));
        ivIcon.setImageResource(R.drawable.my_head_de);
        tvName.setText("未登录");
        if (userBean != null && isLogin()) {

            Glide.with(this)
                    .load(userBean.getUser_face())
                    .asBitmap()
                    .placeholder(R.drawable.my_head_de)
                    .error(R.drawable.my_head_de)
                    .into(ivIcon);

            String name = TextUtils.isEmpty(userBean.getUsername()) ? userBean.getPhone() : userBean.getUsername();
            tvName.setText(name);
            tv_redpkg.setText((userBean.getRedpacketmoney() + "元"));
            tvUserMoney.setText((String.format("%.2f", Double.parseDouble(userBean.getAllmoney())) + "元"));
            tvLogin.setText(name);
            String level = "低";
            if ("2".equals(userBean.getSafe()) || "3".equals(userBean.getSafe()))
                level = "中";
            else if ("1".equals(userBean.getSafe()))
                level = "高";
            tvOnclickLogin.setText(("安全等级:" + level));

            //这里设置用户名；

            if(!TextUtils.isEmpty(userBean.getNickname())){
                mTvNickname.setText(userBean.getNickname());
            }
        }
    }

    @Override
    public void onRefresh() {
        getUserInfo();
    }
}
